package com.kingtroldata.autosort_demo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * 热门标签自动排序工具
 * Created by user on 2017/2/13.
 */

public class AutoSort {
    public static final String AUTOSORT = "AutoSort";
    private static AutoSort mInstance;
    private TreeMap<String, Integer> map = new TreeMap<>();
    private TreeMap<Integer, String> sortMap;

    private AutoSort() {
        getData();
    }

    public static AutoSort init() {
        if (mInstance == null) {
            mInstance = new AutoSort();
        }
        return mInstance;
    }

    public void add(String key) {
        if (map.containsKey(key)) {
            map.put(key, map.get(key) + 1);
        } else {
            map.put(key, 1);
        }
        sort();
    }

    private void sort() {
        sortMap = new TreeMap<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1 == 0 ? 1 : o2 - o1;
            }
        });
        Set<Map.Entry<String, Integer>> entries = map.entrySet();
        for (Map.Entry<String, Integer> entry : entries) {
            String k = entry.getKey();
            Integer v = entry.getValue();
            sortMap.put(v, k);
        }
    }

    /**
     * 获取需要显示的唯一标识
     *
     * @return 返回数据数组
     */
    public String[] getValues(int count) {
        Collection<String> values = sortMap.values();
        int size = values.size();
        String[] array = values.toArray(new String[size]);
        return Arrays.copyOfRange(array, 0, count >= size ? size : count);
    }

    /**
     * 获取排序后的Map集合
     *
     * @return
     */
    public TreeMap<Integer, String> getMap() {
        return sortMap;
    }

    /**
     * 保存数据
     */
    public void savaData() {
        Gson gson = new Gson();
        String json = gson.toJson(map);
        PrefUtils.putString(App.mContext, AUTOSORT, json);
        LoggerUtils.e("将数据保存到SP中");
    }

    /**
     * 获取保存在SP中的数据
     */
    private void getData() {
        String json = PrefUtils.getString(App.mContext, AUTOSORT, null);
        Gson gson = new Gson();
        if (json != null) {
            map = gson.fromJson(json, new TypeToken<TreeMap<String, Integer>>() {
            }.getType());
        }
        LoggerUtils.e("SP读取完毕");
    }
}
